//导入vue和vue-router的包
import Vue from 'vue'
import Router from 'vue-router'
import Login from './components/login.vue'
import Home from './components/home.vue'
import Welcome from './components/welcome.vue'
import Users from './components/user/users.vue'
import Rights from './components/power/rights.vue'
import Roles from './components/power/roles.vue'
import Cate from './components/goods/cate.vue'

//调用Vue.use函数，把VueRouter安装为Vue的插件
Vue.use(Router)

//创建路由实例对象并向外共享路由实例对象
const router= new Router({
  routes: [
    { path: '/', redirect: '/login' },
    { path: '/login', component: Login },//设置login组件路由并重定向
    {
      path: '/home', component: Home, redirect: '/welcome',
      children: [
        { path: '/welcome', component: Welcome },
        { path: '/users', component: Users },
        { path: '/rights', component: Rights },
        { path: '/roles', component: Roles },
        { path: '/categories', component:Cate},
      ]
    },
    
  ]
})
// 挂载路由导航守卫
router.beforeEach((to, from, next) => {
  // to 将要访问的路径
  // from 代表从哪个路径跳转而来
  // next 是一个函数，表示放行
  //     next()  放行    next('/login')  强制跳转
  if (to.path === '/login') return next()
  // 获取token
  const tokenStr = window.sessionStorage.getItem('token')
  //实际开发中我们token还要再返回给后端进行验证 防止过期或假的token 这里只用作理解原理
  if (!tokenStr) return next('/login')//这里是如果token为空
  next()
})

export default router
